import Cookie from "js-cookie";
export default {
  state: {
      isCollapse: false,   //左侧菜单是否展开
      currentMenu: "", //当前点击的导航栏
      menu: [],   //全部导航栏 
      tabList:[    //导航菜单数组
         {
            path: "/",
            name: "home",
            title: "首页",
            icon: "s-home",
         }
      ]  
  },
  getters: {

  },
  mutations: {
      // 点击获取菜单栏
     selectMenu(state,val){   
        if (val.name !== 'home') {
            state.currentMenu = val;
            let result = state.tabList.findIndex(item => item.name === val.name);
            result === -1 ? state.tabList.push(val) : "";
        }else{
            state.currentMenu = null;
        }
       //val.name === "home" ? state.currentMenu = "" : state.currentMenu = val;
     },
     // 关闭/删除菜单按钮
     closeTab(state,val) {
        let result = state.tabList.findIndex(item => item.name === val.name);
        state.tabList.splice(result,1);
     },
     // 点击是否展开左侧菜单栏的方法
     collapseMenu(state){   
       state.isCollapse = !state.isCollapse;   //取反
     },
     // 存储后台返回的菜单路由
     setMenu(state,value){
        state.menu = value;  //返回菜单赋值
        Cookie.set('menu',JSON.stringify(value));
     },
     // 清除路由菜单，用于退出
     clearMenu(state){
        state.menu = [];
        Cookie.remove('menu');
     },
     // 动态添加菜单路由
     addMenu(state,router) {
        if(!Cookie.get('menu')){
           return;
        }
        let menu = JSON.parse(Cookie.get('menu'));
        state.menu = menu;
        let currentMenu = [
           {
              path: '/',
              component: () => import('@/views/index'),
              children: []
           }
        ]
        menu.forEach( item => {
            if (item.children) {
              item.children = item.children.map( item => {
                 item.component = () => import(`@/views/${item.url}`);
                 return item
            })
            currentMenu[0].children.push(...item.children);
            }else{
               item.component = () => import(`@/views/${item.url}`);
               currentMenu[0].children.push(item);
            }
        })
        router.addRoutes(currentMenu);   //动态添加路由
     }
  },
  actions: {

  }
}